package org.sjsu.freedoor.security;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.jboss.resteasy.core.ResourceMethod;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.spi.Failure;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.interception.AcceptedByMethod;
import org.jboss.resteasy.spi.interception.PreProcessInterceptor;

//http://stackoverflow.com/questions/11549268/intercepting-based-on-http-header-in-resteasy
public class ValidationInterceptor implements PreProcessInterceptor, AcceptedByMethod {
	public final boolean CHECK_SECURITY = true;
	public final String SECRET_PASSWORD = "theadjs";

	@Context
	private HttpServletRequest servletRequest;

	@Override
	public boolean accept(Class declaring, Method method) {
		return method.isAnnotationPresent(Securable.class);
	}

	@Override
	public ServerResponse preProcess(HttpRequest httpRequest, ResourceMethod resourceMethod) 
			throws Failure, WebApplicationException {
		
		if(!CHECK_SECURITY)
			return null;

		Securable securable =  resourceMethod.getMethod().getAnnotation(Securable.class);
		String headerValue = servletRequest.getHeader(securable.header());

		if (headerValue == null) {
			return (ServerResponse)Response.status(Status.BAD_REQUEST).entity("Invalid Session").build();
		} else if(!headerValue.equals(SECRET_PASSWORD)) {
			return (ServerResponse)Response.status(Status.UNAUTHORIZED).entity("Invalid Session").build();
		}

		return null;
	}
}